package com.lemon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.lemon.domain.*;
import com.lemon.domain.dto.AlreadyDto;
import com.lemon.domain.dto.EntryUpDto;
import com.lemon.domain.vo.TargetVo;
import com.lemon.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.service.WarehousingEntryUpService;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class WarehousingEntryUpServiceImpl extends ServiceImpl<WarehousingEntryUpMapper, WarehousingEntryUp> implements WarehousingEntryUpService{

    private final WarehousingEntryUpMapper warehousingEntryUpMapper;
    private final WarehousingEntryDetailsMapper warehousingEntryDetailsMapper;
    private final WarehousingEntryMapper warehousingEntryMapper;
    private final WarehousingEntryDetailsMapper entryDetailsMapper;
    private final WarehouseMapper warehouseMapper;
    private final WarehouseAreaMapper warehouseAreaMapper;
    private final WarehouseAreaLocaMapper warehouseAreaLocaMapper;

    @Override
    public List<TargetVo> task(Integer category) {
        List<TargetVo> list = new ArrayList<>();
        if (category == 1){
            // 使用LambdaQueryWrapper进行去重查询
            List<Map<String, Object>> maps = warehousingEntryUpMapper.selectMaps(
                    new QueryWrapper<WarehousingEntryUp>()
                            .select("DISTINCT warehouse_id")
            );

            // 提取并转换warehouse_id值
            List<Integer> warehouseIds = maps.stream()
                                                .map(map -> (Integer) map.get("warehouse_id"))
                                                .filter(Objects::nonNull)
                                                .collect(Collectors.toList());
            warehouseIds.forEach(warehouseId -> {
                TargetVo targetVo = new TargetVo(warehouseId, warehouseMapper.selectById(warehouseId).getName());
                list.add(targetVo);
            });
        } else if (category == 2) {
            // 使用LambdaQueryWrapper进行去重查询
            List<Map<String, Object>> maps = warehousingEntryUpMapper.selectMaps(
                    new QueryWrapper<WarehousingEntryUp>()
                            .select("DISTINCT warehouse_area_id")
            );

            // 提取并转换warehouse_id值
            List<Integer> warehouseAreaIds = maps.stream()
                                                 .map(map -> (Integer) map.get("warehouse_area_id"))
                                                 .filter(Objects::nonNull)
                                                 .collect(Collectors.toList());
            warehouseAreaIds.forEach(warehouseAreaId -> {
                TargetVo targetVo = new TargetVo(warehouseAreaId, warehouseAreaMapper.selectById(warehouseAreaId).getName());
                list.add(targetVo);
            });
        }else if (category == 3) {
            // 使用LambdaQueryWrapper进行去重查询
            List<Map<String, Object>> maps = warehousingEntryUpMapper.selectMaps(
                    new QueryWrapper<WarehousingEntryUp>()
                            .select("DISTINCT warehouse_area_loca_id")
            );

            // 提取并转换warehouse_id值
            List<Integer> warehouseAreaLocaIds = maps.stream()
                                                     .map(map -> (Integer) map.get("warehouse_area_loca_id"))
                                                     .filter(Objects::nonNull)
                                                     .collect(Collectors.toList());
            warehouseAreaLocaIds.forEach(warehouseAreaLocaId -> {
                TargetVo targetVo = new TargetVo(warehouseAreaLocaId, warehouseAreaLocaMapper.selectById(warehouseAreaLocaId).getLocaCode());
                list.add(targetVo);
            });
        }else {
            return new ArrayList<>();
        }
        return list;
    }


    @Override
    @Transactional
    public void add(EntryUpDto entryUpDto) {
        WarehousingEntryUp entryUp = BeanUtil.toBean(entryUpDto, WarehousingEntryUp.class);
        entryUp.setStatus(2);
        entryUp.setCreateTime(LocalDateTime.now());
        warehousingEntryUpMapper.insert(entryUp);
        if (entryUpDto.getCount().equals(entryUpDto.getCountAble())){
            WarehousingEntryDetails entryDetails = warehousingEntryDetailsMapper.selectById(entryUpDto.getEntryDetailsId());
            entryDetails.setStatus(6);
            warehousingEntryDetailsMapper.updateById(entryDetails);
        }
    }
    @Override
    public PageResult getPage(Integer page, Integer pageSize, Integer status) {
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize);
        // 查询满足条件的数据
        List<WarehousingEntryDetails> entryDetailsList = entryDetailsMapper.selectList(
                Wrappers.<WarehousingEntryDetails>lambdaQuery()
                        .eq(WarehousingEntryDetails::getStatus, status)
                        .or()
                        .eq(WarehousingEntryDetails::getStatus, status - 1)
        );
        //List<WarehousingEntryDetails> entryDetailsList = entryDetailsMapper.getUpList(status);
        List<AlreadyDto> list = new ArrayList<>();
        // 处理数据转换
        entryDetailsList.forEach(entryDetails -> {
            List<WarehousingEntryUp> upList = warehousingEntryUpMapper.selectList(
                    Wrappers.<WarehousingEntryUp>lambdaQuery()
                            .eq(WarehousingEntryUp::getEntryDetailsId, entryDetails.getId())
            );
            upList.forEach(up -> {
                AlreadyDto alreadyDto = new AlreadyDto();
                alreadyDto.setId(up.getId());
                WarehousingEntry warehousingEntry = warehousingEntryMapper.selectById(entryDetails.getWarehousingEntryId());
                alreadyDto.setConsignorId(Math.toIntExact(warehousingEntry.getConsignorId()));
                alreadyDto.setConsignorName(warehousingEntry.getConsignorName());
                alreadyDto.setBatchNumber(warehousingEntry.getBatchNumber());
                alreadyDto.setSupplierId(Math.toIntExact(entryDetails.getSupplierId()));
                alreadyDto.setSupplierName(entryDetails.getSupplierName());
                alreadyDto.setRealArrivalTime(entryDetails.getRealArrivalTime());
                alreadyDto.setSkuId(entryDetails.getSkuId());
                alreadyDto.setTitle(entryDetails.getTitle());
                alreadyDto.setCode(entryDetails.getCode());
                alreadyDto.setStatus(entryDetails.getStatus());
                alreadyDto.setCount(up.getCount());
                alreadyDto.setWarehouseId(up.getWarehouseId());
                alreadyDto.setWarehouseName(warehouseMapper.selectById(up.getWarehouseId()).getName());
                alreadyDto.setWarehouseAreaId(up.getWarehouseAreaId());
                alreadyDto.setWarehouseAreaName(warehouseAreaMapper.selectById(up.getWarehouseAreaId()).getName());
                alreadyDto.setWarehouseAreaLocaId(up.getWarehouseAreaLocaId());
                alreadyDto.setWarehouseAreaLocaName(warehouseAreaLocaMapper.selectById(up.getWarehouseAreaLocaId()).getLocaCode());
                list.add(alreadyDto);
            });
        });
        // 正确获取PageInfo对象
        com.github.pagehelper.PageInfo<AlreadyDto> pageInfo = new com.github.pagehelper.PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public List<WarehousingEntryUp> getList(Long skuId) {
        List<WarehousingEntryUp> upList = warehousingEntryUpMapper.selectList(Wrappers.<WarehousingEntryUp>lambdaQuery().eq(WarehousingEntryUp::getSkuId, skuId));
        if (CollUtil.isEmpty(upList)){
            return new ArrayList<>();
        }
        upList.forEach(up -> {
            Warehouse warehouse = warehouseMapper.selectById(up.getWarehouseId());
            up.setWarehouseName(warehouse.getName());
            WarehouseArea warehouseArea = warehouseAreaMapper.selectById(up.getWarehouseAreaId());
            up.setWarehouseAreaName(warehouseArea.getName());
            WarehouseAreaLoca warehouseAreaLoca = warehouseAreaLocaMapper.selectById(up.getWarehouseAreaLocaId());
            up.setLocaCode(warehouseAreaLoca.getLocaCode());
        });
        return upList;
    }


    //@Override
    //public PageResult getPage(Integer page, Integer pageSize, Integer status) {
    //    PageHelper.startPage(page, pageSize);
    //    List<WarehousingEntryDetails> entryDetailsList = entryDetailsMapper.selectList(Wrappers.<WarehousingEntryDetails>lambdaQuery().eq(WarehousingEntryDetails::getStatus, status));
    //    List<WarehousingEntryDetails> entryDetails1 = entryDetailsMapper.selectList(Wrappers.<WarehousingEntryDetails>lambdaQuery().eq(WarehousingEntryDetails::getStatus, status-1));
    //    entryDetailsList.addAll(entryDetails1);
    //    List<AlreadyDto> list = new ArrayList<>();
    //    entryDetailsList.forEach(entryDetails -> {
    //        List<WarehousingEntryUp> upList = warehousingEntryUpMapper.selectList(Wrappers.<WarehousingEntryUp>lambdaQuery().eq(WarehousingEntryUp::getEntryDetailsId, entryDetails.getId()));
    //        upList.forEach(up -> {
    //            AlreadyDto alreadyDto = new AlreadyDto();
    //            alreadyDto.setId(up.getId());
    //            WarehousingEntry warehousingEntry = warehousingEntryMapper.selectById(entryDetails.getWarehousingEntryId());
    //            alreadyDto.setConsignorId(Math.toIntExact(warehousingEntry.getConsignorId()));
    //            alreadyDto.setConsignorName(warehousingEntry.getConsignorName());
    //            alreadyDto.setBatchNumber(warehousingEntry.getBatchNumber());
    //            alreadyDto.setSupplierId(Math.toIntExact(entryDetails.getSupplierId()));
    //            alreadyDto.setSupplierName(entryDetails.getSupplierName());
    //            alreadyDto.setRealArrivalTime(entryDetails.getRealArrivalTime());
    //            alreadyDto.setSkuId(entryDetails.getSkuId());
    //            alreadyDto.setTitle(entryDetails.getTitle());
    //            alreadyDto.setCode(entryDetails.getCode());
    //            alreadyDto.setStatus(entryDetails.getStatus());
    //            alreadyDto.setCount(up.getCount());
    //            alreadyDto.setWarehouseId(up.getWarehouseId());
    //            alreadyDto.setWarehouseName(warehouseMapper.selectById(up.getWarehouseId()).getName());
    //            alreadyDto.setWarehouseAreaId(up.getWarehouseAreaId());
    //            alreadyDto.setWarehouseAreaName(warehouseAreaMapper.selectById(up.getWarehouseAreaId()).getName());
    //            alreadyDto.setWarehouseAreaLocaId(up.getWarehouseAreaLocaId());
    //            alreadyDto.setWarehouseAreaLocaName(warehouseAreaLocaMapper.selectById(up.getWarehouseAreaLocaId()).getLocaCode());
    //            list.add(alreadyDto);
    //        });
    //    });
    //
    //    // 修改Page转换方法 - 正确的方式
    //    Page<AlreadyDto> entryDetailDtoPage = new Page<>();
    //    entryDetailDtoPage.addAll(list);
    //    entryDetailDtoPage.setPageNum(page);
    //    entryDetailDtoPage.setPageSize(pageSize);
    //    // 设置总数，这里需要从查询结果中获取
    //    Page<?> pageInfo = (Page<?>) entryDetailsList;
    //    entryDetailDtoPage.setTotal(pageInfo.getTotal());
    //
    //    return new PageResult(entryDetailDtoPage.getTotal(), entryDetailDtoPage.getResult());
    //}
}
